/**
 * 
 */
package com.noisyair.android.alvin.apps.sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;

/**
 * @author darren
 *
 */
public class IncomingSMSReceiver extends BroadcastReceiver {

	// Why is this not a class yet in the SDK?
	private static final String queryString = "@echo ";
	private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	
	/* (non-Javadoc)
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {

		if(intent.getAction().equals(SMS_RECEIVED)){
			SmsManager smsManager = SmsManager.getDefault();
			
			Bundle bundle = intent.getExtras();
			if (bundle != null){
				Object [] pdus = (Object[])bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[pdus.length];
				for(int i = 0; i<pdus.length; i++){
					messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
				}
				
				for(SmsMessage message : messages){
					String msg = message.getMessageBody();
					String to = message.getOriginatingAddress();
					
					// remove this later
					if(msg.toLowerCase().startsWith(queryString)){
						String out = msg.substring(queryString.length());
						smsManager.sendTextMessage(to, null, out, null, null);
					}
				}
			}
		}
	}

}
